using System.Collections.Generic;
using System.Linq;
using Baik.Interface.Execution;
using Baik.Interface.Expression;
using Baik.Interface.Framework;

namespace Baik.Expression
{
    public class FunctionLiteral : Expression, IFunctionLiteral
    {
        public FunctionLiteral(IInjector inject) : base(inject)
        {}        
        
        public override IObject Evaluate()
        {
            var rtn = Inject.Instantiate<IFunction>();
            rtn.DeclarationScope = EvaluationScope;
            rtn.Params = this.Params.OfType<IReference>().ToList();
            rtn.Expressions = this.Expressions;
            return rtn;
        }
        
        public IEnumerable<IExpression> Params { get; set; }
        public IEnumerable<IExpression> Expressions { get; set; }

        private string pstring()
        {
            var lst = Params as IExpression[] ?? Params.ToArray();
            var sw = new System.IO.StringWriter();
            for (int i = 0; i < lst.Length; i++)
            {
                if(i > 0 )sw.Write(", ");
                sw.Write(lst[i].AsString());
            }
            return sw.ToString();
        }
        private string estring()
        {
            var lst = Expressions as IExpression[] ?? Expressions.ToArray();
            var sw = new System.IO.StringWriter();
            for (int i = 0; i < lst.Length; i++)
            {
                if (lst[i] != null)sw.Write(lst[i].AsString() + ";");
            }
            return sw.ToString();
        }
        public string AsString()
        {
            return "(" + pstring() + "){" + estring() + "}";
        }
    }
}